<?php

namespace app\api\controller;

use app\api\model\Cat;
use app\api\model\Swiper;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Config;
use think\Db;

/**
 * 示例接口
 */
class Wx extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';
    //实例化的小程序应用
    protected $app;
    //实例化的支付应用
    protected $payment;

    public function _initialize()
    {
        parent::_initialize();
        $mp_config     = ['appid' => Config::get('weixin.appid'), 'secret' => Config::get('weixin.secret')];
        $pay_config    = ['app_id' => Config::get('weixin.appid'), 'mch_id' => Config::get('weixin.mchid'), 'key' => Config::get('weixin.key')];
        $this->app     = Factory::miniProgram($mp_config);
        $this->payment = Factory::payment($pay_config);
    }

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */

    public function swiper()
    {
        $res = Swiper::all();
        $this->success('返回成功', $res);
    }

    /**
     * 分类页
     *
     */
    public function cat()
    {
        $res = Cat::with('product')->select();
        $this->success('返回成功', $res);
    }
    //VIP页面
    public function userlevel()
    {
        $res = Db::name('userlevel')->select();
        return json($res);
    }
    /**
     * 微信登陆
     *
     */
    public function login($code)
    {
        $session = $this->app->auth->session($code);
        $openid  = $session['openid'];
        $user    = Db::name('wxuser')->where('openid', $openid)->find();
        if (!$user) {
            Db::name('wxuser')->insert(['openid' => $openid]);
            return json(['openid'=>$openid,'viplevel'=>0]);
        }else{
            return json(['openid'=>$openid,'viplevel'=>$user['viplevel']]);
        }
        
    }
    /**
     * 获取餐桌名称
     *
     */
    public function deskName($desk_id)
    {
        $res = Db::name('desk')->where('id', $desk_id)->find();
        return $res['name'];
    }

    /**
     * 下单
     *
     */
    public function createOrder()
    {
        $params = $this->request->param();
        dump($params);
        $desk_id      = $params['desk_id'];
        $openid       = $params['openid'];
        $total_fee    = $params['total_fee'];
        $out_trade_no = time() . rand(1000, 9999);
        $order_detail = json_decode($params['order_detail'], true);
        //订单数据写入数据库
        Db::name('order')->insert(['desk_id' => $desk_id, 'openid' => $openid, 'total_fee' => $total_fee, 'order_no' => $out_trade_no, 'createtime' => time(), 'status' => 'unpaid']);
        $order_id = Db::name('order')->getLastInsID();
        foreach ($order_detail as $key => $value) {
            Db::name('order_detail')->insert(['order_id' => $order_id, $product_id = $value['id'], $product_name => $value['name'], $product_price => $value['price'], $product_number => $value['number'], $product_image => $value['image']]);
        }
        //微信支付统一下单
        $result = $this->payment->order->unify([
            'body'         => '桌台点餐',
            'out_trade_no' => $out_trade_no,
            'total_fee'    => $total_fee * 100,
            'trade_type'   => 'JSAPI',
            'openid'       => $openid,
            'notify_url'   => $this->request->domain() . '/api/wx/orderCallback',

        ]);
        //再次签名
        $jssdk  = $this->payment->jssdk;
        $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        return json($config);
    }

    /**
     * 订单支付通知
     *
     */
    public function orderCallback()
    {
        $response = $this->payment->handlePaidNotify(function ($message, $fail) {
            $order = Db::name('order')->where('order_no', $message['out_trade_no'])->find();
            if (!$order || $order->paytime) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    Db::name('order')->where('order_no', $message['out_trade_no'])->update(['paytime' => time(), 'transaction_id' => $message['transaction_id'], 'status' => 'paid']);
                }
            }
            return true;
        });
        $response->send();
    }
    /**
     * 购买会员卡
     *
     */
    public function buyVip()
    {
        $params       = $this->request->param();
        $openid       = $params['openid'];
        $total_fee    = $params['total_fee'];
        $level_id    = $params['level_id'];
        $out_trade_no = time() . rand(1000, 9999);

        //订单数据写入数据库
        Db::name('viporder')->insert([ 'openid' => $openid, 'total_fee' => $total_fee, 'order_no' => $out_trade_no, 'createtime' => time(), 'status' => 'unpaid','level_id'=>$level_id]);
        //微信支付统一下单
        $this->payment->order->unify([
            'body'         => '会员充值',
            'out_trade_no' => $out_trade_no,
            'total_fee'    => $total_fee * 100,
            'trade_type'   => 'JSAPI',
            'openid'       => $openid,
            'notify_url'   => $this->request->domain() . '/api/wx/orderCallback',

        ]);
        //再次签名
        $jssdk  = $this->payment->jssdk;
        $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        return json($config);
    }
    /**
     * 购买会员卡支付通知
     *
     */
    public function vipCallback()
    {
        $response = $this->payment->handlePaidNotify(function ($message, $fail) {
            $order = Db::name('viporder')->where('order_no', $message['out_trade_no'])->find();
            if (!$order || $order->paytime) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    Db::name('viporder')->where('order_no', $message['out_trade_no'])->update(['paytime' => time(),'transaction_id' => $message['transaction_id'], 'status' => 'paid']);
                }
            }
            return true;
        });
        $response->send();
    }

}
